package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    //当前模块调用过了其他模块的sevice 对象
    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealService setmealService;

    @Override
    //根据ID删除分类,删除之前加入自己的逻辑判断
    //SELECT COUNT(id) FROM dish WHERE category_id='xxx'
    //SELECT COUNT(id) FROM setmeal WHERE categro_id='xxx'
    public void removeMyId(Long id) {
        //添加查询条件,根据分类ID进行查询菜品数据
        LambdaQueryWrapper<Dish> lqw1=new LambdaQueryWrapper<>();
        lqw1.eq(Dish::getCategoryId,id);
        //SELECT COUNT(id) FROM dish WHERE category_id='xxx'
        int count1=dishService.count(lqw1);
        //如果已经关联菜品,抛出业务异常
        if(count1>0){
            throw  new CustomException("当前分类关联了菜品,不能删除的");
        }
        //添加查询条件,根据分类ID进行查询套餐数据
        LambdaQueryWrapper<Setmeal> lqw2=new LambdaQueryWrapper<>();
        lqw2.eq(Setmeal::getCategoryId,id);
        int count2 = setmealService.count(lqw2);
        //如果已经关联套餐,抛出业务异常
        if(count2>0){
            throw  new CustomException("当前分类关联了套餐,不能删除的");
        }
        //正常删除分类
        super.removeById(id);
    }
}
